const express = require("express");
const { User } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * 获取用户列表
 * GET /admin/users
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [["id", "DESC"]],
      offset,
      limit: pageSize,
    };
    if (query.email) {
      condition.where = {
        email: {
          [Op.eq]: query.email,
        },
      };
    }

    if (query.username) {
      condition.where = {
        username: {
          [Op.eq]: query.username,
        },
      };
    }

    if (query.nickname) {
      condition.where = {
        nickname: {
          [Op.like]: `%${query.nickname}%`,
        },
      };
    }

    if (query.role) {
      condition.where = {
        role: {
          [Op.eq]: query.role,
        },
      };
    }

    const users = await User.findAndCountAll(condition);
    success(res, "Get users successfully", {
      users: users.rows,
      total: users.count,
      currentPage,
      pageSize,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id获取用户
 * GET /admin/users/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const user = await getUser(req);
    success(res, "Get user successfully", { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建用户
 * POST /admin/users
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req.body);
    const user = await User.create(body);
    success(res, "Create user successfully", { user }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除用户
 * DELETE /admin/users/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const user = await getUser(req);
    await user.destroy();
    success(res, "Delete user successfully");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新用户
 * PUT /admin/users/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const user = await getUser(req);
    await user.update(filterBody(req.body));
    success(res, "Update user successfully", { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const {
    email,
    username,
    password,
    nickname,
    sex,
    company,
    introduce,
    role,
    avatar,
  } = body;
  return {
    email,
    username,
    password,
    nickname,
    sex,
    company,
    introduce,
    role,
    avatar,
  };
}

/**
 * 公共方法： 查询当前用户
 */
async function getUser(req) {
  const { id } = req.params;
  const user = await User.findByPk(id);
  if (!user) {
    throw new NotFoundError(`ID: ${id}的用户未找到`);
  }
  return user;
}

module.exports = router;
